// pages/materialSelect/materialSelect.js
import{materialList,warehouseList}from"@/api/material.js";
Page({
  data: {
    materials: [],
    searchKeyword: '',
    allChecked: false,
    selectedCount: 0,
    totalCount: 0,
    warehouses: [],
    warehouseId:null,
    selectedWarehouse:{id:"",name:"选择仓库",value:""},
  },
  onLoad: function() {
    // 示例物料数据
    this.getWarehouse();
    this.getMaterialList();
  },
    // 仓库选择事件
   bindWarehouseChange(e) {
      console.log(e);
      this.setData({
        selectedWarehouse: this.data.warehouses[e.detail.value],
        warehouseId:this.data.warehouses[e.detail.value]["id"]
      });
      this.getMaterialList(this.data.warehouses[e.detail.value]["id"])
    },
// 搜索事件
searchKeyword(e){
  console.log(e);
  this.setData({searchKeyword:e.detail.value})
},
  onSearch() {
    // 实现搜索逻辑
    const name = this.data.searchKeyword;
    const warehouseId = this.data.selectedWarehouse.id;
    console.log(`搜索仓库: ${warehouseId}, 关键字: ${name}`);
    // 实际项目中应添加搜索过滤逻辑
    this.getMaterialList(warehouseId,name)
  },
  //仓库列表
  async getWarehouse(){
    const result=await warehouseList();
    console.log(result);
    this.setData({
      warehouses:[{id:"",name:"全部"},...result.data]
    })
  },
  //耗材列表
  async getMaterialList(warehouseId="",name=""){
    const materials = [
      { id: 1, name: '键盘', code: 'KB001', specification: 'K845', materialNum: 50, checked: false, quantity: 0 }
    ];
    const result=await materialList(warehouseId,name);
    if(result.code===200&&result.data[0]["mlist"]!=null){
      this.setData({
        materials: result.data[0]["mlist"].map(item => ({...item, materialNum:0})),
        totalCount:result.data[0]["total"]
      });
    }else{

    }
    console.log(result);
  },


  // 全选处理
  handleAllChange: function(e) {
    const checked = e.detail.value.length > 0;
    const materials = [...this.data.materials].map(item => ({
      ...item,
      checked,
      materialNum: checked ? 1 : 0
    }));
    this.setData({
      materials,
      allChecked: checked,
      selectedCount: checked ? materials.length : 0
    });
  },

  // 单个项目选择处理
  handleItemChange(e) {
    const index = e.currentTarget.dataset.index;
    const checkedIds = e.detail.value;
    const isChecked = checkedIds.includes(this.data.materials[index].materialId.toString());
    const materials = [...this.data.materials];
    materials[index].checked = isChecked;
    materials[index].materialNum = isChecked ? 1 : 0;
    const allChecked = materials.every(item => item.checked);
    this.setData({
      materials,
      allChecked,
      selectedCount: this.calculateSelectedCount()
    });
  },

  // 计算已选数量
  calculateSelectedCount: function() {
    const selectedCount = this.data.materials.filter(item => item.checked).length;
    this.setData({
      selectedCount,
      totalCount: this.data.materials.length
    });
  },

  // 改变数量
  changeQuantity(e) {
    let index=e.target.dataset.index;
    let type=e.target.dataset.type;
    const materials = [...this.data.materials];
    let materialNum = materials[index].materialNum;
    type==="plus"?materialNum+= 1:materialNum-= 1;
    // 确保数量不小于1且不大于库存
    materialNum = Math.max(1, Math.min(materials[index]["quantity"], materialNum));
    materials[index].materialNum = materialNum;
    this.setData({
      materials
    });
  },

  // 输入数量
  inputQuantity(e) {
    console.log(e.detail);
    const value = parseInt(e.detail.value);
    const index=e.target.dataset.index;
    const materials = [...this.data.materials];
    // 确保输入为有效数字且在1到库存之间
    console.log(isNaN(value));
    if (!isNaN(value)) {
      materials[index].materialNum = Math.max(1, Math.min(value, Number(materials[index].quantity)));
      this.setData({
        materials
      });
    }
  },

  // 确认选择
  confirmSelection: function() {
    if(!this.data.warehouseId){
      wx.showToast({
        title: '请选择仓库',
        icon:"error",
        mask:true
      })
      return
    }
    const selectedMaterials = this.data.materials.filter(item => item.checked).map(item => ({...item, warehouse: this.data.selectedWarehouse}));
    // 返回选中的物料
    wx.navigateBack({
      delta: 1,
      success: () => {
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.emit('selectedMaterials', {
          materials: selectedMaterials,
          warehouseId:this.data.warehouseId
        });
      }
    });
  },

  // 返回上一页
  navigateBack: function() {
    wx.navigateBack({
      delta: 1
    });
  }
})